package cn.kgc.easybuy.controller;

import cn.kgc.easybuy.annotaion.CheckPermission;
import cn.kgc.easybuy.pojo.Address;
import cn.kgc.easybuy.service.AddressService;
import cn.kgc.easybuy.utils.AjaxResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;

/**
 * @program: yingzi-wants-to-sleep
 * @description:
 * @author: 敖成
 * @create: 2025-09-16 17:07
 **/
@RestController
public class AddressController {
    @Autowired
    private AddressService addressService;


    @CheckPermission({"0","1"})
    @GetMapping("/selectAllAddress")
    public AjaxResult selectAllAddress() {
        return AjaxResult.success().add("allAddress", addressService.selectAllAddress());
    }
    @CheckPermission({"0","1"})
    @GetMapping("/selectAddressById")
    public AjaxResult selectAddressById(int id) {
        return AjaxResult.success().add("address", addressService.selectAddressById(id));
    }

    @CheckPermission({"0","1"})
    @GetMapping("/selectAddressByUserId")
    public AjaxResult selectAddressByUserId(int userId) {
        return AjaxResult.success()
                .add("userAddress", addressService.selectAddressByUserId(userId))
                .add("addressNum", addressService.selectAddressByUserId(userId).size());
    }

    @CheckPermission({"0","1"})
    @PostMapping("/addAddress")
    public AjaxResult addAddress(@RequestBody Address address) {
        address.setCreateTime(new Date());
        boolean flag = addressService.addAddress(address);
        if (flag) {
            return AjaxResult.success();
        }else {
            return AjaxResult.error();
        }
    }

    @CheckPermission({"0","1"})
    @PostMapping("/updateAddress")
    public AjaxResult updateAddress(@RequestBody Address address) {
        boolean flag = addressService.updateAddress(address);
        if (flag) {
            return AjaxResult.success();
        }else {
            return AjaxResult.error();
        }
    }
    @CheckPermission({"0","1"})
    @GetMapping("/deleteAddress")
    public AjaxResult deleteAddress(int id) {
        boolean flag = addressService.deleteAddressById(id);
        if (flag) {
            return AjaxResult.success();
        }else {
            return AjaxResult.error();
        }
    }

    @CheckPermission({"0","1"})
    @GetMapping("/selectDefaultAddress")
    public AjaxResult selectDefaultAddress(int userId) {
        return AjaxResult.success().add("defaultAddress", addressService.selectDefaultAddress(userId));
    }
}
